import React, { useEffect, useState } from 'react';
import { useGame } from '../GameContext';
import { motion } from 'framer-motion';

const OrderQueue: React.FC = () => {
  const { state, selectOrder, deliverPizza, takePizzaFromOven } = useGame();
  const { orders, currentOrderId } = state;
  const [timeRemaining, setTimeRemaining] = useState<Record<string, number>>({});

  // 更新订单剩余时间
  useEffect(() => {
    const updateTime = () => {
      const now = Date.now();
      const newTimeRemaining: Record<string, number> = {};
      
      orders.forEach(order => {
        if (order.status === 'pending' || order.status === 'in-progress') {
          const elapsed = (now - order.createdAt) / 1000;
          newTimeRemaining[order.id] = Math.max(0, order.timeLimit - elapsed);
        }
      });
      
      setTimeRemaining(newTimeRemaining);
    };

    // 立即更新一次
    updateTime();
    
    // 每秒更新一次
    const interval = setInterval(updateTime, 1000);
    
    return () => clearInterval(interval);
  }, [orders]);

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
  };

  // 获取订单状态的文本和颜色
  const getOrderStatusInfo = (status: string) => {
    switch (status) {
      case 'pending':
        return { text: '待处理', color: 'text-blue-500' };
      case 'in-progress':
        return { text: '进行中', color: 'text-yellow-500' };
      case 'completed':
        return { text: '已完成', color: 'text-green-500' };
      case 'failed':
        return { text: '已失败', color: 'text-red-500' };
      default:
        return { text: '未知', color: 'text-gray-500' };
    }
  };

  return (
    <div className="game-card">
      <h2 className="text-2xl font-bold text-amber-800 mb-4">订单队列</h2>
      <div className="space-y-2 max-h-[600px] overflow-y-auto pr-2">
        {orders.length === 0 ? (
          <motion.div 
            className="text-center text-gray-500 py-4"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
          >
            暂无订单
          </motion.div>
        ) : (
          orders.filter(order => order.status !== 'completed').map((order) => {
            const statusInfo = getOrderStatusInfo(order.status);
            const isSelected = currentOrderId === order.id;
            const remaining = timeRemaining[order.id] || 0;
            const isUrgent = remaining < 10 && (order.status === 'pending' || order.status === 'in-progress');

            return (
              <motion.div
                key={order.id}
                className={`order-card ${isSelected ? 'selected' : ''} ${order.status}`}
                onClick={() => selectOrder(order.id)}
                initial={{ x: -50, opacity: 0 }}
                animate={{ x: 0, opacity: 1 }}
                exit={{ x: 50, opacity: 0 }}
                transition={{ duration: 0.3 }}
                whileHover={{ scale: 1.02 }} onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); const pizzaType = e.dataTransfer.getData('pizzaType'); const slotId = e.dataTransfer.getData('slotId'); if (pizzaType && slotId && !isNaN(parseInt(slotId))) { const success = deliverPizza(order.id, pizzaType); if (success) takePizzaFromOven(parseInt(slotId)); } }}
                whileTap={{ scale: 0.98 }}
              >
                <div className="flex justify-between items-center">
                  <div>
                    <h3 className="font-bold text-lg">{order.pizzaType}披萨</h3>
                    <p className={`text-sm ${statusInfo.color}`}>{statusInfo.text}</p>
                  </div>
                  {(order.status === 'pending' || order.status === 'in-progress') && (
                    <div className={`font-mono ${isUrgent ? 'text-red-500 font-bold' : 'text-gray-600'}`}>
                      {formatTime(remaining)}
                    </div>
                  )}
                </div>
                
                {order.status === 'pending' && (
                  <motion.div 
                    className="w-full h-1 bg-gray-200 mt-2 rounded-full overflow-hidden"
                    initial={{ width: '100%' }}
                    animate={{ width: `${(remaining / order.timeLimit) * 100}%` }}
                  >
                    <div className={`h-full ${isUrgent ? 'bg-red-500' : 'bg-blue-500'}`}></div>
                  </motion.div>
                )}
              </motion.div>
            );
          })
        )}
      </div>
    </div>
  );
};

export default OrderQueue;